<?php 
class Cellphonezone_Repay_Model_Order_Repay
{	
	public function __construct()
    {
        $this->_helper = Mage::helper('repay');  
    }
    
	public function savePayment ($data)
	{
		if (empty($data)) {
            return array('error' => -1, 'message' => $this->_helper->__('Invalid data.'));
        }
        $_order = $this->getOrder();
        if (!$_order)
        {
        	return $this;
        }
        if ($_order->isVirtual()) {
            $_order->getBillingAddress()->setPaymentMethod(isset($data['method']) ? $data['method'] : null);
        } else {
            $_order->getShippingAddress()->setPaymentMethod(isset($data['method']) ? $data['method'] : null);
        }

        // shipping totals may be affected by payment method
        if (!$_order->isVirtual() && $_order->getShippingAddress()) {
            $_order->getShippingAddress()->setCollectShippingRates(true);
        }

        $payments = $_order->getAllPayments();
         
        if ($payments[0])
        {
        	$payment = $payments[0];
        }
        else 
        {
        	$payment = mage::getModel('sales/order_payemnt');
        }
        if (!$payment->getId())
        {
        	$payment->setOrder($_order);
        }
        $payment->setMethod($data['method']);

        $_order->setPayment($payment);

        $_order->collectTotals();

        $_order->save();
	}
	
	public function getRedirectUrl()
	{
		$_order = $this->getOrder();
		$payments = $_order->getAllPayments();
		if ($payments[0])
        {
        	$payment = $payments[0];
        }
        else 
        {
        	$payment = mage::getModel('sales/order_payemnt');
        }
        if (!$payment->getId())
        {
        	$payment->setOrder($_order);
        }
        $redirectUrl = $payment->getMethodInstance()->getOrderPlaceRedirectUrl();
        if ($redirectUrl)
        {
        	$redirectUrl = Mage::getUrl(substr($redirectUrl,strlen(Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK,true))),array('order_id' => $_order->getId()));
        }
		return $redirectUrl;
	}
    /**
     * Retrieve current order model instance
     *
     * @return Mage_Sales_Model_Order
     */
    public function getOrder()
    {
        return Mage::registry('current_order');
    }
    	
}
?>